package com.zzvcom.office.convert;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Converter;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

// 泛型版本的对象转JSON转换器
@Converter
public class ObjectToJsonConverter<T> implements AttributeConverter<T, String> {

    private static final ObjectMapper objectMapper = new ObjectMapper();
    private final Class<T> targetType;

    static {
        // 禁用默认类型信息（避免序列化时包含类名）
        objectMapper.disableDefaultTyping();
    }

    @SuppressWarnings("unchecked")
    public ObjectToJsonConverter() {
        // 通过反射获取泛型类型
        Type superclass = getClass().getGenericSuperclass();
        ParameterizedType parameterizedType = (ParameterizedType) superclass;
        this.targetType = (Class<T>) parameterizedType.getActualTypeArguments()[0];
    }

    @Override
    public String convertToDatabaseColumn(T attribute) {
        if (attribute == null) {
            return null;
        }
        try {
            return objectMapper.writeValueAsString(attribute);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Failed to serialize object to JSON", e);
        }
    }

    @Override
    public T convertToEntityAttribute(String dbData) {
        if (dbData == null) {
            return null;
        }
        try {
            // 使用泛型类型进行反序列化
            return objectMapper.readValue(dbData, targetType);
        } catch (IOException e) {
            throw new RuntimeException("Failed to deserialize JSON to object", e);
        }
    }
}